<template>
	<view class="vh-100 w-p-100 poster text-white overflow-hidden">
		<canvas class="cv" canvas-id="canvas" id="canvas" :style="`width:100%;height:${ctxHeight}px;`"></canvas>
		<view class="box">
			<swiper :current="current" class="h-490" previous-margin="40rpx" next-margin="40rpx" @change="onChange">
				<swiper-item class="swiper-item-card round h-490 relative"
					:class="{'swiper-item-card-margin':current!=index}" v-for="(item, index) in posterList"
					:key="index">
					<view :style="`background-image:url(${item.src})`" class="round-12 card-img p-12 flex flex-column"
						:class="{'card-margin':current!=index,'img':current==index}">
						<view class="flex flex-center gap-4">
							<image :src="WEBCONFIG?.web_logo" class="round-circle w-28" mode="widthFix"></image>
							<text class="fw-600 text-white">{{WEBCONFIG?.web_name}}</text>
						</view>
						<view class="flex-1 flex flex-x-flex-end flex-column">
							<view class="w-p-100 bg-white round-12 p-12 flex gap-4 ">
								<view class="flex flex-column gap-6 flex-1">
									<view class="flex flex-y-center gap-6">
										<view class="w-45 h-45">
											<image :src="USERINFO?.avatar?USERINFO?.avatar:WEBCONFIG?.web_logo"
												class="w-45 h-45 round-circle"></image>
										</view>
										<view class="flex flex-column gap-2">
											<text
												class="text-brown-1 fs-15 text-ellipsis-1 fw-600">{{USERINFO?.nickname}}</text>
											<text
												class="fs-11 text-999 text-ellipsis-1">邀请您加入{{WEBCONFIG?.web_name}}</text>
										</view>
									</view>
									<view class="flex flex-y-center text-black gap-4 w-p-100">
										<text class="fs-18 fw-600 ">扫码立即加入</text>
									</view>
								</view>
								<view class="qrcode bg-grey-1" style="width: 85px;">
									<image :src="qrcode" class="qrcode"></image>
								</view>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
			<view class="flex flex-x-space-between px-20 gap-10 mt-30">
				<view class="border-white py-9 px-30 round-12 wa fs-18" @click="initCanvas">保存图片</view>
				<button class="btn-normal bg-white round-12 text-black py-9 flex-1 text-center fs-18 "
					open-type="share">
					<view class="flex flex-center">
						马上邀请好友
					</view>
				</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { getCurrentInstance, onMounted, ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app'
	import system from '@/utils/system';
	import { useRefs, useUserStore, useWebConfigStore } from '@/stores'
	import { $http, $tool, $page } from '@/utils';

	const instance = getCurrentInstance();
	const { USERINFO } = useRefs(useUserStore())
	const { WEBCONFIG } = useRefs(useWebConfigStore())
	const { getUserInfo } = useUserStore()
	const current = ref(0)
	const posterList = [
		{ src: system.domain + '/app/ycSora/image/1.jpg' },
		{ src: system.domain + '/app/ycSora/image/2.jpg' },
	];

	const bgList = [
		'/app/ycSora/image/1.jpg',
		'/app/ycSora/image/2.jpg',
	];

	const qrcode = ref('')
	const onChange = (e) => {
		current.value = e.detail.current
	}
	const saveImage = async () => {
		const res = await uni.canvasToTempFilePath({
			x: 0,
			y: 0,
			width: mobileSystem.windowWidth,
			height: ctxHeight.value,
			destWidth: mobileSystem.windowWidth,
			destHeight: ctxHeight.value,
			canvasId: 'canvas'
		}, instance.proxy)
		// #ifdef MP-WEIXIN
		uni.saveImageToPhotosAlbum({
			filePath: res.tempFilePath,
			success(res) {
				uni.hideLoading()
				$tool.toast('保存成功')
			}
		})
		// #endif

		//#ifdef H5
		uni.showToast({
			title: '请长按图片-保存至相册'
		})
		//#endif
	}

	onLoad(() => {
		uni.showLoading({
			title: '加载中...'
		})
		// #ifdef MP-WEIXIN
		if (USERINFO?.value.applet_qrcode) {
			qrcode.value = USERINFO?.value.applet_qrcode
		}
		// #endif

		// #ifdef H5
		if (!USERINFO?.value.h5_qrcode) {
			qrcode.value = USERINFO?.value.h5_qrcode
		}
		// #endif
		getQrcode()
	})

	const getQrcode = () => {
		if (qrcode.value != '' && qrcode.value != null) {
			uni.hideLoading()
			return;
		}
		let source = 'applet';
		// #ifdef H5
		source = 'h5'
		// #endif
		$http.get('User/getQrcode', { source: source }).then(res => {
			qrcode.value = res.data.url
			getUserInfo()
		})
	}
	const ctxHeight = ref(0)
	//系统参数
	const mobileSystem = uni.getSystemInfoSync()
	let ctx;
	// const initCanvas = async () => {
	// 	ctx = uni.createCanvasContext('canvas', instance.proxy);

	// 	// 获取必要数据
	// 	const avatar = USERINFO.value.avatar ? USERINFO.value.avatar : WEBCONFIG?.value.web_logo;
	// 	const title = WEBCONFIG?.value.web_name || '';

	// 	// 获取图像资源
	// 	const [bgImg, avatarImg, qrcodeImg, logo] = await Promise.all([
	// 		uni.getImageInfo({ src: posterList[current.value].src }),
	// 		uni.getImageInfo({ src: avatar }),
	// 		uni.getImageInfo({ src: qrcode.value }),
	// 		uni.getImageInfo({ src: WEBCONFIG?.value.web_logo })
	// 	]);

	// 	// 缩放背景图
	// 	const scale = mobileSystem.windowWidth / bgImg.width;
	// 	ctxHeight.value = bgImg.height * scale;

	// 	// 绘制背景
	// 	ctx.clearRect(0, 0, mobileSystem.windowWidth, ctxHeight.value);
	// 	ctx.drawImage(bgImg.path, 0, 0, mobileSystem.windowWidth, ctxHeight.value);

	// 	// 绘制顶部 logo + 标题
	// 	const logoSize = 25;
	// 	const titleFontSize = 18;
	// 	ctx.setFontSize(titleFontSize);
	// 	ctx.setFillStyle('#000');
	// 	ctx.setTextBaseline('middle');

	// 	const gap = 8;
	// 	const titleWidth = ctx.measureText(title).width;
	// 	const totalWidth = logoSize + gap + titleWidth;
	// 	const startX = (mobileSystem.windowWidth - totalWidth) / 2;
	// 	const centerY = 40;

	// 	ctx.drawImage(logo.path, startX, centerY - logoSize / 2, logoSize, logoSize);
	// 	ctx.fillText(title, startX + logoSize + gap, centerY);

	// 	// 绘制底部白色圆角矩形
	// 	const rectX = 12;
	// 	const rectY = ctxHeight.value - 130;
	// 	const rectWidth = mobileSystem.windowWidth - 24;
	// 	const rectHeight = 120;
	// 	const radius = 10;
	// 	drawRoundRect(rectX, rectY, rectWidth, rectHeight, radius);
	// 	ctx.setFillStyle('#fff');
	// 	ctx.fill();

	// 	// 绘制头像
	// 	const offsetX = 10;
	// 	const offsetY = 10;
	// 	const avatarRadius = 30;
	// 	const avatarCenterX = 44.5 + offsetX;
	// 	const avatarCenterY = ctxHeight.value - 98 + offsetY;

	// 	ctx.save();
	// 	ctx.beginPath();
	// 	ctx.arc(avatarCenterX, avatarCenterY, avatarRadius, 0, Math.PI * 2);
	// 	ctx.clip();
	// 	const avatarDrawSize = avatarRadius * 2;
	// 	ctx.drawImage(
	// 		avatarImg.path,
	// 		avatarCenterX - avatarRadius,
	// 		avatarCenterY - avatarRadius,
	// 		avatarDrawSize,
	// 		avatarDrawSize
	// 	);
	// 	ctx.restore();

	// 	// 绘制二维码（固定右侧）
	// 	const qrSize = 100;
	// 	const qrPadding = 10;
	// 	const qrX = rectX + rectWidth - qrSize - qrPadding;
	// 	const qrY = rectY + (rectHeight - qrSize) / 2;
	// 	ctx.drawImage(qrcodeImg.path, qrX, qrY, qrSize, qrSize);

	// 	// 可绘制文本区域宽度
	// 	const textStartX = avatarCenterX + avatarRadius + 6;
	// 	const maxTextWidth = qrX - textStartX - 10;

	// 	// 截断文本函数
	// 	const ellipsisText = (ctx, text, maxWidth) => {
	// 		if (ctx.measureText(text).width <= maxWidth) return text;
	// 		while (ctx.measureText(text + '...').width > maxWidth && text.length > 0) {
	// 			text = text.slice(0, -1);
	// 		}
	// 		return text + '...';
	// 	};

	// 	const userName = USERINFO?.value.nickname || '';
	// 	const userDesc = '邀请您加入' + title;

	// 	const displayName = ellipsisText(ctx, userName, maxTextWidth);
	// 	// const displayDesc = ellipsisText(ctx, userDesc, maxTextWidth);

	// 	// 绘制用户名
	// 	const nameY = avatarCenterY - 10;
	// 	ctx.setFillStyle('#EE8B2E');
	// 	ctx.setFontSize(20);
	// 	ctx.setTextBaseline('middle');
	// 	ctx.fillText(displayName, textStartX, nameY);

	// 	// 绘制描述
	// 	const descY = avatarCenterY + 15;
	// 	ctx.setFillStyle('#878787');
	// 	ctx.setFontSize(14);
	// 	ctx.fillText(displayDesc, textStartX, descY);

	// 	// 绘制 “扫码立即加入”
	// 	const joinText = '扫码立即加入';
	// 	ctx.setFillStyle('#000000');
	// 	ctx.setTextBaseline('top');
	// 	ctx.font = 'normal bold 20px sans-serif';
	// 	const joinTextWidth = ctx.measureText(joinText).width;
	// 	const joinTextX = qrX + (qrSize - joinTextWidth) / 2;
	// 	const joinTextY = qrY + qrSize + 8;
	// 	ctx.fillText(joinText, joinTextX, joinTextY);

	// 	// 最后渲染并保存
	// 	ctx.draw(false, () => {
	// 		saveImage();
	// 	});
	// };

	const initCanvas = async () => {
		console.log(13)
		try {
			ctx = uni.createCanvasContext('canvas', instance.proxy);
			const avatar = USERINFO.value.avatar ? USERINFO.value.avatar : WEBCONFIG?.value.web_logo
			// 获取背景图信息
			const bgImg = await uni.getImageInfo({ src: posterList[current.value].src });
			// 获取头像图片信息
			const avatarImg = await uni.getImageInfo({ src: avatar });
			// 二维码图片
			const qrcodeImg = await uni.getImageInfo({ src: qrcode.value });
			// 获取图标
			const logo = await uni.getImageInfo({ src: WEBCONFIG?.value.web_logo })
			const title = WEBCONFIG?.value.web_name
			const scale = mobileSystem.windowWidth / bgImg.width;
			ctxHeight.value = bgImg.height * scale;
			ctx.clearRect(0, 0, mobileSystem.windowWidth, ctxHeight.value);
			ctx.drawImage(bgImg.path, 0, 0, mobileSystem.windowWidth, ctxHeight.value);
			const logoSize = 25;
			const titleFontSize = 18;
			ctx.setFontSize(titleFontSize);
			ctx.setFillStyle('#000');
			ctx.setTextBaseline('middle');
			// 绘制白色圆角矩形底框
			const rectX = 12;
			const rectY = ctxHeight.value - 130;
			const rectWidth = mobileSystem.windowWidth - 24;
			const rectHeight = 120;
			const radius = 10;
			drawRoundRect(rectX, rectY, rectWidth, rectHeight, radius);
			ctx.setFillStyle('#fff');
			ctx.fill();
			console.log(1)
			// 头像和文本偏移量
			const offsetX = 10;
			const offsetY = 10;
			// 头像圆心坐标
			const avatarRadius = 30;
			const avatarCenterX = 44.5 + offsetX;
			const avatarCenterY = ctxHeight.value - 98 + offsetY;
			// 绘制头像圆形裁剪区域
			ctx.save();
			ctx.beginPath();
			ctx.arc(avatarCenterX, avatarCenterY, avatarRadius, 0, Math.PI * 2);
			ctx.clip();
			const avatarDrawSize = avatarRadius * 2;
			const avatarDrawX = avatarCenterX - avatarRadius;
			const avatarDrawY = avatarCenterY - avatarRadius;
			ctx.drawImage(avatarImg.path, avatarDrawX, avatarDrawY, avatarDrawSize, avatarDrawSize);
			ctx.restore();
			// 绘制文本
			let titleWidth = ctx.measureText ? ctx.measureText(title).width : title.length * titleFontSize;
			const gap = 8;
			const totalWidth = logoSize + gap + titleWidth;
			const startX = (mobileSystem.windowWidth - totalWidth) / 2;
			const centerY = 30;
			ctx.drawImage(logo.path, startX, centerY - logoSize / 2, logoSize, logoSize);
			ctx.fillText(title, startX + logoSize + gap, centerY);
			const textStartX = avatarCenterX + avatarRadius + 6;
			const nameY = avatarCenterY - 10;
			const descY = avatarCenterY + 15;
			let userName = USERINFO?.value.nickname;
			const userDesc = '邀请您加入' + title;
			ctx.setFillStyle('#EE8B2E');
			ctx.setFontSize(20);
			ctx.setTextBaseline('middle');

			// ✅ 昵称过长省略逻辑
			const maxNameWidth = 120; // 最大显示宽度，可根据UI微调
			if (ctx.measureText) {
				const nameWidth = ctx.measureText(userName).width;
				if (nameWidth > maxNameWidth) {
					while (ctx.measureText(userName + '...').width > maxNameWidth && userName.length > 0) {
						userName = userName.slice(0, -1);
					}
					userName += '...';
				}
			}

			ctx.fillText(userName, textStartX, nameY);
			ctx.setFillStyle('#878787');
			ctx.setFontSize(14);
			ctx.fillText(userDesc, textStartX, descY);
			const joinText = '扫码立即加入';
			ctx.setFillStyle('#000000'); // 黑色
			ctx.setTextBaseline('top');
			console.log(1)
			ctx.font = 'normal bold 20px sans-serif';
			const textWidth = ctx.measureText ? ctx.measureText(joinText).width : 0;
			const joinTextX = avatarCenterX - avatarRadius;
			const joinTextY = avatarCenterY + avatarRadius + 15;
			ctx.fillText(joinText, joinTextX, joinTextY);
			console.log(1)
			// 新增绘制二维码
			const qrSize = 100; // 二维码宽高
			const qrX = rectX + rectWidth - qrSize - 10; // 白色矩形右边界减去二维码宽度再减10px
			const qrY = rectY + (rectHeight - qrSize) / 2; // 垂直居中
			ctx.drawImage(qrcodeImg.path, qrX, qrY, qrSize, qrSize);
			// 最后渲染
			ctx.draw(false, () => {
				saveImage()
			})
		} catch (err) {
			console.log(err)
		}
	}



	const drawRoundRect = (x, y, width, height, radius) => {
		ctx.beginPath()
		ctx.moveTo(x + radius, y)
		ctx.lineTo(x + width - radius, y)
		ctx.quadraticCurveTo(x + width, y, x + width, y + radius)
		ctx.lineTo(x + width, y + height - radius)
		ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height)
		ctx.lineTo(x + radius, y + height)
		ctx.quadraticCurveTo(x, y + height, x, y + height - radius)
		ctx.lineTo(x, y + radius)
		ctx.quadraticCurveTo(x, y, x + radius, y)
		ctx.closePath()
	}
</script>

<style>
	.poster {
		background-repeat: no-repeat;
		background-size: 100% 100%;
	}

	.box {
		padding: 30px 0px;
	}

	.card-img {
		width: 100%;
		height: 100%;
		overflow: hidden;
		background-size: 100% 100%;
		background-repeat: no-repeat;
	}

	.img {
		border: 1px solid rgba(255, 255, 255, 0.4);
		box-sizing: border-box;
	}

	.swiper-item-card {
		width: 92% !important;
		height: 100%;
		margin: 0 4%;
		overflow: hidden;
		box-sizing: border-box;
		display: flex;
		align-items: flex-start;
		justify-content: center;
	}

	.swiper-item-card-margin {
		padding: 4% 0;
	}


	.card-margin {
		width: calc(100% - 80rpx);
		margin: 0 20rpx;
		overflow: hidden;
	}

	.h-490 {
		height: 980rpx;
	}

	.h-45 {
		height: 90rpx;
	}

	.w-45 {
		width: 90rpx;
	}

	.qrcode {
		width: 166rpx;
		height: 166rpx;
	}

	.cv {
		position: fixed;
		top: -10000px;
	}
</style>